package rpg.update
{
	import flash.geom.Rectangle;

	import rpg.Utils.GameUtils;
	import rpg.Utils.Val;
	import rpg.avatar.AvatarComponent;
	import rpg.role.Hero;
	import rpg.state.StateComponent;

	/**
	 * 摄像头
	 * @author hyy
	 *
	 */
	public class CameraUpdate extends Update
	{
		private static var instance : CameraUpdate;
		/**
		 * 英雄在屏幕的位置
		 */
		public static var sceneX : int;
		public static var sceneY : int;

		/**
		 * 镜头跟进的英雄
		 */
		public static var aimHero : Hero;
		/**
		 * 自己的角色可行走的区域
		 */
		public var walkRect : Rectangle = new Rectangle();

		private var avatarComponent : AvatarComponent;

		public function CameraUpdate()
		{
		}

		public static function getInstance() : CameraUpdate
		{
			if(instance == null)
			{
				instance = new CameraUpdate();
				instance.registerd(HIGHT);
			}
			return instance;
		}


		override public function update(delay : uint) : void
		{
			if(aimHero == null)
				return;
			//往左走
			if(sceneX < walkRect.x)
			{
				if(aimHero.mapX < walkRect.x)
					sceneX = aimHero.mapX;
				else
					sceneX = walkRect.x;
			}
			//往右走
			else if(sceneX > walkRect.x + walkRect.width)
			{
				//if(GameUtils.stageWidth - (GameUtils.sceneWidth - aimHero.mapX) > walkRect.x + walkRect.width)
				if((GameUtils.sceneWidth - aimHero.mapX) < walkRect.x)
					sceneX = GameUtils.stageWidth - (GameUtils.sceneWidth - aimHero.mapX);
				else
					sceneX = walkRect.x + walkRect.width;
			}

			//往上走
			if(sceneY < walkRect.y)
			{
				if(aimHero.mapY < walkRect.y)
					sceneY = aimHero.mapY;
				else
					sceneY = walkRect.y;
			}
			//往下走
			else if(sceneY > walkRect.y + walkRect.height)
			{
				if((GameUtils.sceneHeight - aimHero.mapY) < walkRect.y)
					sceneY = GameUtils.stageHeight - (GameUtils.sceneHeight - aimHero.mapY);
				else
					sceneY = walkRect.y + walkRect.height;
			}

			GameUtils.viewX = aimHero.mapX - sceneX;
			GameUtils.viewY = aimHero.mapY - sceneY;
		}

		/**
		 * 设置摄像头的焦点
		 *
		 */
		public function setFocus(hero : Hero) : void
		{
			aimHero = hero;
			avatarComponent = aimHero.getComponent(AvatarComponent);
			sceneX = GameUtils.stageWidth / 2;
			sceneX = GameUtils.stageHeight / 2;
		}
	}
}